<template>
  <div class="finance-management">
    <div class="page-header">
      <h1 class="page-title">财务管理</h1>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
          新增记录
        </el-button>
        <el-button :icon="Histogram" @click="showReportDialog = true">
          财务报表
        </el-button>
        <el-button :icon="Document" @click="showBudgetDialog = true">
          预算管理
        </el-button>
        <el-button :icon="Download" @click="exportData">
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 财务概览卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card income">
          <div class="stat-content">
            <div class="stat-icon" style="background: #67C23A;">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ (financeStats.totalIncome / 10000).toFixed(1) }}万</div>
              <div class="stat-label">总收入</div>
              <div class="stat-trend positive">
                <el-icon><ArrowUp /></el-icon>
                +12.5%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card expense">
          <div class="stat-content">
            <div class="stat-icon" style="background: #F56C6C;">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ (financeStats.totalExpense / 10000).toFixed(1) }}万</div>
              <div class="stat-label">总支出</div>
              <div class="stat-trend negative">
                <el-icon><ArrowDown /></el-icon>
                -5.2%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card profit">
          <div class="stat-content">
            <div class="stat-icon" style="background: #409EFF;">
              <el-icon><PieChart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ (financeStats.profit / 10000).toFixed(1) }}万</div>
              <div class="stat-label">净利润</div>
              <div class="stat-trend positive">
                利润率: {{ financeStats.profitMargin }}%
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card pending" @click="showPendingDialog = true">
          <div class="stat-content">
            <div class="stat-icon" style="background: #E6A23C;">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ financeStats.pendingApproval }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchQuery"
            placeholder="搜索记录描述、相关人员"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterType" placeholder="收支类型" clearable @change="handleFilter">
            <el-option label="收入" value="收入" />
            <el-option label="支出" value="支出" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterCategory" placeholder="分类" clearable @change="handleFilter">
            <el-option label="门诊收入" value="门诊收入" />
            <el-option label="住院收入" value="住院收入" />
            <el-option label="药品收入" value="药品收入" />
            <el-option label="药品采购" value="药品采购" />
            <el-option label="设备采购" value="设备采购" />
            <el-option label="人员工资" value="人员工资" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="状态" clearable @change="handleFilter">
            <el-option label="待审核" value="待审核" />
            <el-option label="已审核" value="已审核" />
            <el-option label="已拒绝" value="已拒绝" />
            <el-option label="已入账" value="已入账" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateRangeChange"
            style="width: 100%"
          />
        </el-col>
      </el-row>
    </el-card>

    <!-- 财务记录列表 -->
    <el-card shadow="never">
      <el-table
        :data="paginatedRecords"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="记录编号" width="100" />
        <el-table-column prop="date" label="日期" width="110" />
        <el-table-column prop="type" label="类型" width="80">
          <template #default="{ row }">
            <el-tag :type="row.type === '收入' ? 'success' : 'danger'" size="small">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="{ row }">
            <span :class="row.type === '收入' ? 'amount-income' : 'amount-expense'">
              {{ row.type === '收入' ? '+' : '-' }}¥{{ row.amount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="{ row }">
            <el-tag :type="getPaymentMethodColor(row.paymentMethod)" size="small">
              {{ row.paymentMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="relatedName" label="关联对象" width="120" />
        <el-table-column prop="departmentName" label="科室" width="100" />
        <el-table-column prop="operator" label="操作员" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleApprove(row)"
              v-if="row.status === '待审核'"
            >
              审核
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleEdit(row)"
              v-if="['待审核', '已拒绝'].includes(row.status)"
            >
              编辑
            </el-button>
            <el-dropdown @command="(command: string) => handleMoreActions(command, row)">
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="invoice" v-if="row.type === '收入'">
                    开具发票
                  </el-dropdown-item>
                  <el-dropdown-item command="receipt">
                    打印凭证
                  </el-dropdown-item>
                  <el-dropdown-item command="export">
                    导出记录
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" :disabled="row.status === '已入账'">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredRecords.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑财务记录对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingRecord ? '编辑财务记录' : '新增财务记录'"
      width="700px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="recordForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录类型" prop="type">
              <el-radio-group v-model="recordForm.type">
                <el-radio label="收入">收入</el-radio>
                <el-radio label="支出">支出</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期" prop="date">
              <el-date-picker
                v-model="recordForm.date"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="category">
              <el-select v-model="recordForm.category" placeholder="请选择分类">
                <el-option 
                  v-for="category in (recordForm.type === '收入' ? incomeCategories : expenseCategories)" 
                  :key="category"
                  :label="category"
                  :value="category"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input-number
                v-model="recordForm.amount"
                :min="0"
                :precision="2"
                placeholder="金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="recordForm.paymentMethod" placeholder="请选择支付方式">
                <el-option label="现金" value="现金" />
                <el-option label="银行卡" value="银行卡" />
                <el-option label="微信" value="微信" />
                <el-option label="支付宝" value="支付宝" />
                <el-option label="医保" value="医保" />
                <el-option label="转账" value="转账" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室">
              <el-select v-model="recordForm.departmentId" placeholder="请选择科室">
                <el-option 
                  v-for="dept in departments" 
                  :key="dept.id"
                  :label="dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="recordForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入记录描述"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发票号">
              <el-input v-model="recordForm.invoiceNumber" placeholder="发票号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税额">
              <el-input-number
                v-model="recordForm.taxAmount"
                :min="0"
                :precision="2"
                placeholder="税额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 财务详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="财务记录详情"
      width="600px"
    >
      <div v-if="currentRecord" class="record-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录编号">{{ currentRecord.id }}</el-descriptions-item>
          <el-descriptions-item label="记录类型">
            <el-tag :type="currentRecord.type === '收入' ? 'success' : 'danger'">
              {{ currentRecord.type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="日期">{{ currentRecord.date }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ currentRecord.category }}</el-descriptions-item>
          <el-descriptions-item label="子分类">{{ currentRecord.subcategory }}</el-descriptions-item>
          <el-descriptions-item label="金额">
            <span :class="currentRecord.type === '收入' ? 'amount-income' : 'amount-expense'">
              {{ currentRecord.type === '收入' ? '+' : '-' }}¥{{ currentRecord.amount.toFixed(2) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ currentRecord.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="关联对象">{{ currentRecord.relatedName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="科室">{{ currentRecord.departmentName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="操作员">{{ currentRecord.operator }}</el-descriptions-item>
          <el-descriptions-item label="发票号">{{ currentRecord.invoiceNumber || '无' }}</el-descriptions-item>
          <el-descriptions-item label="税额">{{ currentRecord.taxAmount ? `¥${currentRecord.taxAmount}` : '无' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusColor(currentRecord.status)">
              {{ currentRecord.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="审核人">{{ currentRecord.approver || '未审核' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentRecord.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(currentRecord.updatedAt) }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ currentRecord.description }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 财务报表对话框 -->
    <el-dialog
      v-model="showReportDialog"
      title="财务报表"
      width="900px"
    >
      <div class="report-content">
        <el-empty description="财务报表功能开发中" />
      </div>
    </el-dialog>

    <!-- 预算管理对话框 -->
    <el-dialog
      v-model="showBudgetDialog"
      title="预算管理"
      width="900px"
    >
      <div class="budget-content">
        <el-table :data="budgets" border>
          <el-table-column prop="departmentName" label="科室" />
          <el-table-column prop="category" label="预算类别" />
          <el-table-column prop="allocated" label="预算金额">
            <template #default="{ row }">
              ¥{{ row.allocated.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="used" label="已使用">
            <template #default="{ row }">
              ¥{{ row.used.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="remaining" label="剩余">
            <template #default="{ row }">
              ¥{{ row.remaining.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column label="使用率">
            <template #default="{ row }">
              <el-progress 
                :percentage="(row.used / row.allocated * 100)" 
                :color="getProgressColor(row.used / row.allocated)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="getBudgetStatusColor(row.status)">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 待审核记录对话框 -->
    <el-dialog
      v-model="showPendingDialog"
      title="待审核记录"
      width="900px"
    >
      <el-table :data="pendingRecords" max-height="400">
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">
            <el-tag :type="row.type === '收入' ? 'success' : 'danger'" size="small">
              {{ row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" />
        <el-table-column prop="amount" label="金额">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="operator" label="操作员" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleQuickApprove(row)">
              通过
            </el-button>
            <el-button type="text" size="small" @click="handleQuickReject(row)">
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Download, Search, ArrowDown, ArrowUp, TrendCharts, 
  Money, PieChart, Warning, Histogram, Document
} from '@element-plus/icons-vue'
import { useFinanceStore, type FinanceRecord } from '@/stores/modules/finance'
import { useDepartmentStore } from '@/stores/modules/department'

const financeStore = useFinanceStore()
const departmentStore = useDepartmentStore()

// 响应式数据
const searchQuery = ref('')
const filterType = ref('')
const filterCategory = ref('')
const filterStatus = ref('')
const dateRange = ref<[Date, Date] | null>(null)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const showReportDialog = ref(false)
const showBudgetDialog = ref(false)
const showPendingDialog = ref(false)

const editingRecord = ref<FinanceRecord | null>(null)
const selectedRecords = ref<FinanceRecord[]>([])
const loading = ref(false)

// 表单相关
const formRef = ref()
const recordForm = ref({
  type: '收入' as '收入' | '支出',
  category: '',
  subcategory: '',
  amount: 0,
  description: '',
  date: new Date().toISOString().split('T')[0],
  paymentMethod: '现金' as FinanceRecord['paymentMethod'],
  relatedId: '',
  relatedType: undefined as FinanceRecord['relatedType'],
  relatedName: '',
  departmentId: '',
  departmentName: '',
  operator: '当前用户',
  operatorId: 'U001',
  status: '待审核' as FinanceRecord['status'],
  invoiceNumber: '',
  taxAmount: 0
})

// 表单验证规则
const formRules = {
  type: [
    { required: true, message: '请选择记录类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 分类选项
const incomeCategories = ['门诊收入', '住院收入', '药品收入', '检查收入', '治疗收入', '其他收入']
const expenseCategories = ['药品采购', '设备采购', '设备维护', '人员工资', '办公支出', '其他支出']

// 计算属性
const filteredRecords = computed(() => {
  let result = financeStore.financeRecords
  
  if (searchQuery.value) {
    result = financeStore.searchFinanceRecords(searchQuery.value)
  }
  
  if (filterType.value) {
    result = result.filter(r => r.type === filterType.value)
  }
  
  if (filterCategory.value) {
    result = result.filter(r => r.category === filterCategory.value)
  }
  
  if (filterStatus.value) {
    result = result.filter(r => r.status === filterStatus.value)
  }
  
  if (dateRange.value) {
    const [start, end] = dateRange.value
    const startDate = start.toISOString().split('T')[0]
    const endDate = end.toISOString().split('T')[0]
    result = result.filter(r => r.date >= startDate && r.date <= endDate)
  }
  
  return result
})

const paginatedRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRecords.value.slice(start, end)
})

const currentRecord = computed(() => financeStore.currentRecord)
const financeStats = computed(() => financeStore.getFinanceStats())
const budgets = computed(() => financeStore.getBudgets())
const departments = computed(() => departmentStore.departments)

const pendingRecords = computed(() => {
  return financeStore.financeRecords.filter(r => r.status === '待审核')
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleDateRangeChange = () => {
  currentPage.value = 1
}

const handleSelectionChange = (selection: FinanceRecord[]) => {
  selectedRecords.value = selection
}

const handleRowClick = (row: FinanceRecord) => {
  financeStore.currentRecord = row
}

const handleViewDetail = (record: FinanceRecord) => {
  financeStore.currentRecord = record
  showDetailDialog.value = true
}

const handleEdit = (record: FinanceRecord) => {
  editingRecord.value = record
  Object.assign(recordForm.value, record)
  showAddDialog.value = true
}

const handleApprove = async (record: FinanceRecord) => {
  try {
    await ElMessageBox.confirm(
      `确定要审核通过"${record.description}"吗？`,
      '确认审核',
      {
        confirmButtonText: '通过',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await financeStore.approveFinanceRecord(record.id, '财务主管')
    ElMessage.success('审核通过')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('审核失败')
    }
  }
}

const handleMoreActions = async (command: string, record: FinanceRecord) => {
  if (command === 'invoice') {
    ElMessage.info('开具发票功能开发中')
  } else if (command === 'receipt') {
    ElMessage.info('打印凭证功能开发中')
  } else if (command === 'export') {
    ElMessage.info('导出记录功能开发中')
  } else if (command === 'delete') {
    try {
      await ElMessageBox.confirm(
        `确定要删除财务记录"${record.description}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      
      // 这里需要实现删除逻辑
      ElMessage.success('删除成功')
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
}

const handleSave = async () => {
  try {
    await formRef.value.validate()
    
    // 设置科室名称
    if (recordForm.value.departmentId) {
      const department = departments.value.find(d => d.id === recordForm.value.departmentId)
      if (department) {
        recordForm.value.departmentName = department.name
      }
    }
    
    if (editingRecord.value) {
      await financeStore.updateFinanceRecord(editingRecord.value.id, recordForm.value)
      ElMessage.success('更新成功')
    } else {
      await financeStore.addFinanceRecord(recordForm.value)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

const resetForm = () => {
  editingRecord.value = null
  formRef.value?.resetFields()
  Object.assign(recordForm.value, {
    type: '收入',
    category: '',
    subcategory: '',
    amount: 0,
    description: '',
    date: new Date().toISOString().split('T')[0],
    paymentMethod: '现金',
    relatedId: '',
    relatedType: undefined,
    relatedName: '',
    departmentId: '',
    departmentName: '',
    operator: '当前用户',
    operatorId: 'U001',
    status: '待审核',
    invoiceNumber: '',
    taxAmount: 0
  })
}

const handleQuickApprove = async (record: FinanceRecord) => {
  try {
    await financeStore.approveFinanceRecord(record.id, '财务主管')
    ElMessage.success('审核通过')
  } catch (error) {
    ElMessage.error('审核失败')
  }
}

const handleQuickReject = async (record: FinanceRecord) => {
  try {
    await financeStore.rejectFinanceRecord(record.id, '财务主管')
    ElMessage.success('审核拒绝')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const exportData = () => {
  ElMessage.info('导出功能开发中')
}

// 样式辅助方法
const getPaymentMethodColor = (method: string) => {
  const colorMap: Record<string, string> = {
    '现金': 'primary',
    '银行卡': 'success',
    '微信': 'success',
    '支付宝': 'warning',
    '医保': 'info',
    '转账': 'primary'
  }
  return colorMap[method] || 'info'
}

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '待审核': 'warning',
    '已审核': 'success',
    '已拒绝': 'danger',
    '已入账': 'primary'
  }
  return colorMap[status] || 'info'
}

const getBudgetStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '草稿': 'info',
    '已提交': 'warning',
    '已审批': 'primary',
    '执行中': 'success',
    '已完成': 'success'
  }
  return colorMap[status] || 'info'
}

const getProgressColor = (rate: number) => {
  if (rate >= 0.9) return '#F56C6C'
  if (rate >= 0.7) return '#E6A23C'
  return '#67C23A'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

onMounted(() => {
  financeStore.getFinanceRecords()
  departmentStore.getDepartments()
})
</script>

<style lang="scss" scoped>
.finance-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.stats-cards {
  margin-bottom: 20px;

  .stat-card {
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    &.pending:hover {
      border-color: #E6A23C;
    }

    .stat-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 24px;
      }

      .stat-info {
        .stat-value {
          font-size: 24px;
          font-weight: 700;
          color: #303133;
          line-height: 1;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 4px;
        }

        .stat-trend {
          display: flex;
          align-items: center;
          font-size: 12px;
          font-weight: 600;
          margin-top: 4px;

          &.positive {
            color: #67C23A;
          }

          &.negative {
            color: #F56C6C;
          }

          .el-icon {
            margin-right: 2px;
          }
        }
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;
}

.amount-income {
  color: #67C23A;
  font-weight: 600;
}

.amount-expense {
  color: #F56C6C;
  font-weight: 600;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.record-detail {
  .amount-income {
    color: #67C23A;
    font-weight: 600;
  }

  .amount-expense {
    color: #F56C6C;
    font-weight: 600;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
      flex-wrap: wrap;
    }
  }

  .stats-cards {
    :deep(.el-col) {
      margin-bottom: 16px;
    }
  }

  .search-card {
    :deep(.el-row) {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>